package dq.study.concurrent.threadpool;

import java.util.concurrent.CompletableFuture;

/**
 * thenApply与thenAccept测试
 *
 * @author dongqun
 * @version 1.0.0
 * @since 2020/12/22 10:30:00
 */
public class CompletionStageDemo {
    public static void main(String[] args) {
        thenCombine();
    }

    public static void thenApplyAndThenAccept() {
        CompletableFuture.completedFuture("FUTURE")
                //返回值传给下一阶段
                .thenApply(r -> r.toLowerCase())
                //处理上一阶段的数据，但是没返回值
                .thenAccept(f -> System.out.println("--" + f))
                //结果为null
                .thenAccept(f -> System.out.println("**" + f))
                // 返回FUTURE
                .thenApply(f -> new String("FUTURE"))
                // 输出FUTURE，但是没返回值
                .thenAccept(f -> System.out.println(f));
    }


    public static void thenCombine() {
        String result = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (1 == 1) {
                throw new RuntimeException("测试一下异常情况");
            }

            return "hello ";
        }).thenCombine(CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("return world...");  //会执行
            return "world";
        }), (s1, s2) -> {
            String s = s1 + " " + s2;   //并不会执行
            System.out.println("combine result :" + s); //并不会执行
            return s;
        }).whenComplete((s, t) -> {
            System.out.println("current result is :" + s);
            if (t != null) {
                System.out.println("阶段执行过程中存在异常：");
                t.printStackTrace();
            }
        }).join();

        System.out.println("final result:" + result); //并不会执行
    }
}
